<template>
  <div>
    <AModal
      v-bind="$attrs"
      width="800px"
      :body-style="{ padding: '0px' }"
      @close="modalEvent('close')"
      @ok="modalEvent('ok')"
      @open="modalEvent('open')"
      @cancel="modalEvent('cancel')"
    >
      <AScrollbar style="max-height: calc(100vh - 170px); overflow: auto; padding: 20px">
        <AForm ref="formRef" :model="form" auto-label-width layout="vertical">
          <ARow :gutter="10">
            <ACol :span="12">
              <AFormItem
                field="customerId"
                label="客户"
                :rules="[{ required: true, message: '请输入客户名称' }]"
                :validate-trigger="['change', 'input', 'blur']"
              >
                <ASelect
                  v-model="form.customerId"
                  placeholder="输入客户名进行搜索"
                  allow-search
                  @change="formEvent('billTime')"
                >
                  <AOption
                    v-for="item in customerList"
                    :key="item.customerId"
                    :label="item.customerName"
                    :value="item.customerId"
                  ></AOption>
                </ASelect>
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem
                field="billTime"
                label="对账时间"
                :rules="[{ required: true, message: '请输入对账时间' }]"
                :validate-trigger="['change', 'input', 'blur']"
              >
                <ARangePicker
                  v-model="form.billTime"
                  :placeholder="['对帐时间', '对帐时间']"
                  value-format="YYYY-MM-DD"
                  @change="formEvent('billTime')"
                />
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="historyUnreceiveAmt" label="上期末剩余未收取（含税）">
                {{ `¥${formatPrice(form.historyUnreceiveAmt, 1)}` }}
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="historyUnreceiveExclTaxAmt" label="上期末剩余未收取（不含税）">
                {{ `¥${formatPrice(form.historyUnreceiveExclTaxAmt, 1)}` }}
              </AFormItem>
            </ACol>
            <ACol>
              <AFormItem
                field="detailList"
                label="送货单"
                :pagination="false"
                :content-flex="false"
              >
                <ATable
                  :data="deliveryList"
                  :bordered="{ cell: true }"
                  :scroll="{ maxHeight: 300 }"
                  :pagination="false"
                  size="small"
                  column-resizable
                  :loading="deliveryLoad"
                >
                  <template #columns>
                    <ATableColumn title="送货单号" data-index="deliveryOrderCode" :width="150">
                    </ATableColumn>
                    <ATableColumn title="送货日期" data-index="deliveryDate" :width="100">
                      <template #cell="{ record }">
                        <span v-if="record.deliveryDate">
                          {{ dayjs(record.deliveryDate).format('YYYY-MM-DD') }}
                        </span>
                      </template>
                    </ATableColumn>
                    <ATableColumn title="产品名称" data-index="productName" :width="170">
                      <template #cell="{ record }">
                        <div>
                          {{ record.detailList?.map((item) => item.materialName).join(',') }}
                        </div>
                      </template>
                    </ATableColumn>
                    <ATableColumn title="金额" data-index="amt" :width="100">
                      <template #cell="{ record }">
                        <span>
                          {{ `¥${formatPrice(sumBy(record.detailList, 'amt'), 1)}` }}
                        </span>
                      </template>
                    </ATableColumn>
                    <ATableColumn title="含税" data-index="isInclTax" :width="60" align="center">
                      <template #cell="{ record }">
                        <icon-check-circle-fill
                          v-if="record.isInclTax"
                          style="color: #67c23a"
                          size="20px"
                        />
                        <icon-close-circle-fill
                          v-if="!record.isInclTax"
                          style="color: red"
                          size="20px"
                        />
                      </template>
                    </ATableColumn>
                  </template>
                </ATable>
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="curReceivableAmt" label="本期应收金额（含税）">
                <AInputNumber
                  v-model="form.curReceivableAmt"
                  model-event="input"
                  placeholder="本期应收金额（含税）"
                  hide-button
                  :precision="2"
                  :step="0.1"
                />
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="curReceivableExclTaxAmt" label="本期应收金额（不含税）">
                <AInputNumber
                  v-model="form.curReceivableExclTaxAmt"
                  model-event="input"
                  placeholder="本期应收金额（不含税）"
                  hide-button
                  :precision="2"
                  :step="0.1"
                />
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="curReceivedAmt" label="本期已收金额（含税）">
                <AInputNumber
                  v-model="form.curReceivedAmt"
                  model-event="input"
                  placeholder="本期已收金额（含税）"
                  hide-button
                  :precision="2"
                  :step="0.1"
                />
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="curReceivedExclTaxAmt" label="本期已收金额（不含税）">
                <AInputNumber
                  v-model="form.curReceivedExclTaxAmt"
                  model-event="input"
                  placeholder="本期已收金额（不含税）"
                  hide-button
                  :precision="2"
                  :step="0.1"
                />
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="writeAmt" label="核销金额">
                <AInputNumber
                  v-model="form.writeAmt"
                  model-event="input"
                  placeholder="核销金额"
                  hide-button
                  :precision="2"
                  :step="0.1"
                />
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="sellers" label="业务员">
                <ASelect v-model="form.sellersId" allow-search allow-clear placeholder="业务员">
                  <AOption
                    v-for="(item, index) in employeeList"
                    :key="index"
                    :label="item.employeeName"
                    :value="item.employeeId"
                  ></AOption>
                </ASelect>
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="remainReceivableAmt" label="本期末累计未收取（含税）">
                <AInputNumber
                  v-if="(attrs.title as string).includes('新增')"
                  v-model="form.remainReceivableAmt"
                  model-event="input"
                  placeholder="本期末累计未收取（含税）"
                  hide-button
                  :precision="2"
                  :step="0.1"
                />
                <div v-else>${{ formatPrice(form.remainReceivableAmt) }}</div>
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="remainReceivableExclTaxAmt" label="本期末累计未收取（不含税）">
                <AInputNumber
                  v-if="(attrs.title as string).includes('新增')"
                  v-model="form.remainReceivableExclTaxAmt"
                  model-event="input"
                  placeholder="本期末累计未收取（不含税）"
                  hide-button
                  :precision="2"
                  :step="0.1"
                />
                <div v-else>${{ formatPrice(form.remainReceivableExclTaxAmt) }}</div>
              </AFormItem>
            </ACol>

            <ACol :span="12">
              <AFormItem field="billDesc" label="对账情况">
                <ASelect v-model="form.billDesc" placeholder="对账情况" allow-search>
                  <AOption value="1">已对账</AOption>
                  <AOption value="0">未对账</AOption>
                </ASelect>
              </AFormItem>
            </ACol>
            <ACol>
              <AFormItem field="remark" label="附件">
                <upload v-model:attach-files="attachFiles"></upload>
              </AFormItem>
            </ACol>
            <ACol>
              <AFormItem field="remark" label="备注">
                <ATextarea v-model="form.remark" placeholder="备注"></ATextarea>
              </AFormItem>
            </ACol>
          </ARow>
        </AForm>
      </AScrollbar>
    </AModal>
  </div>
</template>

<script lang="ts" setup>
import { Message } from '@arco-design/web-vue'
import dayjs from 'dayjs'
import { formatPrice } from '@renderer/utils/mixins'
import { DeliveryResItem, getDeliveryAllList } from '@renderer/api/logisticsDep'
import { deleteNullObject } from '@renderer/utils/data-processing'
import upload from '@renderer/components/upload/index.vue'
import {
  AccountsReq,
  AccountsResItem,
  editAccounts,
  getAccountsDetail,
  getBillHistoryUnreceiveAmt
} from '@renderer/api/statement'
import { CustomerResItem, getCustomerAllList } from '@renderer/api/company'
import { useMenuState } from '@renderer/store'
import { FileListType } from '@renderer/types/global'
import { differenceBy, isEmpty, sumBy } from 'lodash-es'
import { batchDelUploadFile } from '@renderer/api/common'
import { EmployeeResItem, getEmployeeAllList } from '@renderer/api/employee'

interface Props {
  [key: string]: any
  checkData?: Partial<AccountsResItem>
}
const props = withDefaults(defineProps<Props>(), {
  checkData: () => {
    return {}
  }
})
const emit = defineEmits(['update:visible', 'reload'])
const attrs = useAttrs()
const formRef = ref()
const form = ref<AccountsReq>({
  customerId: '',
  curReceivableAmt: 0,
  historyUnreceiveAmt: 0,
  curReceivedAmt: 0,
  writeAmt: 0,
  remainReceivableAmt: 0,
  sellers: '',
  billDesc: '',
  billType: 0,
  remark: '',
  detailList: [],
  fileList: [],
  billStartDate: '',
  billEndDate: '',
  billTime: [],
  sellersId: '',
  curReceivableExclTaxAmt: 0,
  historyUnreceiveExclTaxAmt: 0,
  curReceivedExclTaxAmt: 0,
  remainReceivableExclTaxAmt: 0
})
const attachFiles = ref<FileListType[]>([])
const menuParam = useMenuState()
const deliveryList = ref<DeliveryResItem[]>([])
const employeeList = ref<EmployeeResItem[]>([])
const deliveryLoad = ref(false)

watchEffect(() => {
  form.value.remainReceivableExclTaxAmt =
    form.value.curReceivableExclTaxAmt +
    form.value.historyUnreceiveExclTaxAmt -
    form.value.curReceivedExclTaxAmt -
    form.value.writeAmt
})
watchEffect(() => {
  form.value.remainReceivableAmt =
    form.value.curReceivableAmt + form.value.historyUnreceiveAmt - form.value.curReceivedAmt
})

// 获取员工列表
const getEmployee = () => {
  getEmployeeAllList({}).then((res) => {
    employeeList.value = res.data.list
  })
}

// 获取客户
const customerList = ref<CustomerResItem[]>([])
const getCustomerList = async () => {
  const res = await getCustomerAllList({})
  customerList.value = res.data.list
}
// 获取详情
const getDetail = () => {
  getAccountsDetail({ billId: props.checkData.billId! }).then((res) => {
    form.value = res.data
    form.value.billTime = [res.data.billStartDate, res.data.billEndDate]
    attachFiles.value = form.value.fileList ? [...form.value.fileList] : []
    deliveryList.value = res.data.detailList
  })
}
// 获取往期的数据
const getHistoryData = () => {
  getBillHistoryUnreceiveAmt({
    billType: 0,
    billStartDate: form.value.billStartDate,
    billEndDate: form.value.billEndDate,
    customerId: form.value.customerId
  }).then((res) => {
    form.value.historyUnreceiveAmt = res.data.historyUnreceiveAmt
    form.value.historyUnreceiveExclTaxAmt = res.data.historyUnreceiveExclTaxAmt
    form.value.curReceivedAmt = res.data.curReceivedAmt
    form.value.curReceivedExclTaxAmt = res.data.curReceivedExclTaxAmt
  })
}

// 表单事件
const formEvent = (type: string) => {
  switch (type) {
    case 'billTime': {
      if (isEmpty(form.value.billTime) || !form.value.customerId) {
        return
      }
      deliveryLoad.value = true
      const [deliveryStartDate, deliveryEndDate] = form.value.billTime || []
      form.value.billStartDate = deliveryStartDate || ''
      form.value.billEndDate = deliveryEndDate || ''
      const temp = customerList.value.find((item) => item.customerId === form.value.customerId)
      getDeliveryAllList({
        deliveryStartDate: deliveryStartDate,
        deliveryEndDate: deliveryEndDate,
        customerName: temp?.customerName,
        isVoid: 0
      }).then((res) => {
        deliveryList.value = res.data.list
        form.value.curReceivableExclTaxAmt = sumBy(res.data.list, (item) =>
          item.isInclTax ? 0 : sumBy(item.detailList, 'amt')
        )
        form.value.curReceivableAmt = sumBy(res.data.list, (item) =>
          item.isInclTax ? sumBy(item.detailList, 'amt') : 0
        )

        deliveryLoad.value = false
      })
      getHistoryData()
      break
    }

    default:
      break
  }
}
// 弹窗事件
const modalEvent = (type: string) => {
  switch (type) {
    case 'ok':
      formRef.value.validate((errors) => {
        if (!errors) {
          form.value.billType = 0
          const delFile = differenceBy(form.value.fileList, attachFiles.value)
          const delFileIds = delFile?.map((item) => item.fileId)
          form.value.fileList = attachFiles.value
          // 新增
          if ((attrs.title as string).includes('新增')) {
            form.value.billId = undefined
          }
          form.value.detailList = deliveryList.value?.map((item) => {
            return {
              relatedOrderId: item.deliveryOrderId!,
              relatedOrderCode: item.deliveryOrderCode!,
              amt: item.totalAmt || 0
            }
          })
          batchDelUploadFile({ fileIdList: delFileIds }).then(() => {
            editAccounts(deleteNullObject(form.value)).then(() => {
              Message.success((attrs.title as string).includes('新增') ? '新增成功' : '修改成功')
              modalEvent('cancel')
              emit('reload')
            })
          })
        }
      })
      break
    case 'close':
      menuParam.switchEditStatus(false)
      formRef.value.resetFields()
      deliveryList.value = []
      emit('update:visible', false)
      break
    case 'open':
      menuParam.switchEditStatus(true)
      getCustomerList()
      getEmployee()
      if (attrs.title === '修改') {
        getDetail()
      }
      break
    case 'cancel':
      formRef.value.resetFields()
      menuParam.switchEditStatus(false)
      deliveryList.value = []
      emit('update:visible', false)
      break
    default:
      break
  }
}
</script>
<style scoped></style>
